﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Honestysoft.Baseframework.WebUI;
using Honestysoft.Workflow.Model;
using Honestysoft.Workflow.BusinessFacade;
using System.Data;
using Honestysoft.BaseObject;
using Honestysoft.Financing.Model;

namespace Honestysoft.Financing.WebUI.UIFramework
{
    public partial class Main : System.Web.UI.Page
    {
        public string FunctionID
        {
            get
            {
                object obj = ViewState["FunctionID"];
                return obj == null ? "" : obj.ToString();
            }
            set
            {
                ViewState["FunctionID"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FunctionID = Request.QueryString["FunctionID"];
                BindSummary();
                BindTask();
                //BindDone();
                BindLast();
                //BindSummaryMonth();
            }
        }


        private void BindTask()
        {
            WFApply.Work IWork = new WFApply.Work(Globals.CurrentConnStringName);
            List<WFWorkItem> lsTask = IWork.GetWorkItemList(UserLoginer.LoginUser.ID, "1002", WFEnumData.WorkItemType.ToDo);
            if (lsTask == null || lsTask.Count == 0) {  return; }
            lblToDoCount.Text = lsTask.Count.ToString();
            List<string> lsId = new List<string>();
            foreach (WFWorkItem item in lsTask)
            {
                lsId.Add(item.BuDataID);
            }
            if (lsId.Count > 0)
            {
                QueryParameters query = new QueryParameters();
                query.Add("ID", lsId, QueryParameters.OperatorType.IN);
                DataTable ToDoTable = new BaseBusinessLogic<Bu_AuditTable>(Globals.CurrentConnStringName).GetTable(query);
                DataRow[] rows=null;
                foreach (WFWorkItem item in lsTask)
                {
                    rows = ToDoTable.Select("ID='" + item.BuDataID + "'");
                    if (rows != null && rows.Length == 1)
                    {
                        item.BuDataCode = rows[0]["TableType"].ToString();
                        item.BuDataSubject = rows[0]["Code"].ToString() + "（" + rows[0]["ProjectName"].ToString() + "）";
                    }
                }
            }
            rptWaitfor.DataSource = lsTask;
            rptWaitfor.DataBind();
        }

        private string curString(string s, int length)
        {
            if (s.Length < length) { return s; }
            return s.Substring(0, length) + "...";
        }

        protected string GetPageUrl(string dataId,string subject, string tableType)
        {
            string page = "AuditTable_Edit";
            //if (tableType == "A") 
            //{
            //    page = "Bu_AuditTable_View";
            //}
            //else if (tableType == "B")
            //{
            //    page = "AuditTable_B";
            //}
            //else if (tableType == "C")
            //{
            //    page = "AuditTable_C";
            //}
            return string.Format("<a href=\"#\" title='{3}' onclick=\"javascript:openwindow('../Module/Audit/{0}.aspx?ID={1}&FunctionID={2}','{3}');\" >{4}</a>", page, dataId, FunctionID,"", curString(subject, 31));
        }

        //private void BindDone()
        //{
        //    WFApply.Work IWork = new WFApply.Work(Globals.CurrentConnStringName);
        //    List<WFWorkItem> lsTask = IWork.GetWorkItemList(UserLoginer.LoginUser.ID, "1002", WFEnumData.WorkItemType.HaveDone);
        //    if (lsTask == null || lsTask.Count == 0) { return; }
        //    //lblDoneCount.Text = lsTask.Count.ToString();
        //    List<string> lsId = new List<string>();
        //    foreach (WFWorkItem item in lsTask)
        //    {
        //        lsId.Add(item.BuDataID);
        //    }
        //    if (lsId.Count > 0)
        //    {
        //        QueryParameters query = new QueryParameters();
        //        query.Add("ID", lsId, QueryParameters.OperatorType.IN);
        //        DataTable ToDoTable = new BaseBusinessLogic<Bu_AuditTable>(Globals.CurrentConnStringName).GetTable(query);
        //        DataRow[] rows = null;
        //        foreach (WFWorkItem item in lsTask)
        //        {
        //            rows = ToDoTable.Select("ID='" + item.BuDataID + "'");
        //            if (rows != null && rows.Length == 1)
        //            {
        //                item.BuDataCode = rows[0]["TableType"].ToString();
        //                item.BuDataSubject = rows[0]["Code"].ToString() + "（" + rows[0]["ProjectName"].ToString() + "）";
        //            }
        //        }
        //    }
        //    rptHaveDone.DataSource = lsTask;
        //    rptHaveDone.DataBind();
        //}

        private void BindLast()
        {
            DataTable dt = new Honestysoft.Financing.BusinessLogic.Audit(Globals.CurrentConnStringName).GetLastBatchAuditTable();
            rptNew.DataSource = dt;
            rptNew.DataBind();
        }

        protected string Url_Month = "";
        protected string Url_Week = "";
        protected string Url_Summary = "";

        private void BindSummary()
        {
            DateTime startDate = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            DateTime endDate = DateTime.Now.AddMonths(1).AddDays(-DateTime.Now.AddMonths(1).Day);
            Url_Month = Globals.Home + "Module/Reports/AuditSummary.aspx?StartDate=" + startDate.ToString("yyyy-MM-dd") + "&EndDate=" + endDate.ToString("yyyy-MM-dd") + "&IsDispBF=1";
            //本周
            DateTime currentDate = DateTime.Now.Date;
            int dayOfWeek = (int)currentDate.DayOfWeek;
            // 以星期日为第一天时，第一天为
            startDate = currentDate.AddDays(-dayOfWeek);
            // 最后一天
            endDate = startDate.AddDays(6);
            Url_Week = Globals.Home + "Module/Reports/AuditSummary.aspx?StartDate=" + startDate.ToString("yyyy-MM-dd") + "&EndDate=" + endDate.ToString("yyyy-MM-dd") + "&IsDispBF=0";
            Url_Summary = Globals.Home + "Module/Reports/AuditSummary.aspx?StartDate=1900-01-01&EndDate=" + DateTime.Today.ToString("yyyy-MM-dd") + "&IsDispBF=1";
        }

        #region 周选择
        ///// <summary>
        ///// 绑定周次下拉框
        ///// </summary>
        //protected void initWeekNumAndTime()
        //{
        //    //得到当前日期是今年第几周了
        //    DateTime dtLastDate = new DateTime(DateTime.Now.Year + 1, 1, 1).AddDays(-1);
        //    int iLastWeekNumber = GetWeekOnYear(dtLastDate);      //本年最后是多少周 
        //    int iCurrentWeekNumber = GetWeekOnYear(DateTime.Now); //当前是第几周
        //    for (int iNum = 1; iNum <= iLastWeekNumber; iNum++)
        //    {
        //        ListItem li = new ListItem(iNum.ToString(), iNum.ToString());
        //        ddlWeek.Items.Add(li);
        //    }
        //    ddlWeek.SelectedValue = iCurrentWeekNumber.ToString();
        //}
        ///// <summary>
        ///// 得到指定日期是今年第几周
        ///// </summary>
        ///// <param name="dt">要得到所在周数的日期</param>
        ///// <returns>今年的第几周</returns>
        //protected int GetWeekOnYear(DateTime dt)
        //{
        //    //如果今年第一天是星期天，则刚好用当今天数/7 取整,如果余数大于0 则再加一
        //    //如果为星期天，则在当今天数减掉（7－？）/7 再加上1，再加上余数是否大于一
        //    //用来表示今天第一天是星期几
        //    int d1 = (int)DateTime.Parse(DateTime.Now.Year.ToString() + "-01-01").DayOfWeek;
        //    //用来表示当前时间是今年的第几天
        //    int dAys = (int)dt.DayOfYear;
        //    int weekon = 0;
        //    if (d1 != 7)
        //    {
        //        //不是星期天
        //        weekon = 1;
        //        dAys = dAys - (7 - d1);
        //    }
        //    weekon += (dAys / 7);
        //    if (dAys % 7 > 0)
        //    {
        //        weekon++;
        //    }
        //    return weekon;
        //}
        #endregion

        //protected string Count_Project = "", Count_Owner = "", Count_Contract = "", Count_Batch = "", Count_AT = "", Amount = "", totalAmount = "";
        //private void BindSummaryMonth()
        //{
        //    DataTable dt = new Honestysoft.Financing.BusinessLogic.Reports(Globals.CurrentConnStringName).GetSummaryByMonth();
        //    if (dt != null && dt.Rows.Count == 1)
        //    {
        //        Count_Project = dt.Rows[0]["Count_Project"].ToString();
        //        Count_Owner = dt.Rows[0]["Count_Owner"].ToString();
        //        Count_Contract = dt.Rows[0]["Count_Contract"].ToString();
        //        Count_Batch = dt.Rows[0]["Count_Batch"].ToString();
        //        Count_AT = dt.Rows[0]["Count_AT"].ToString();
        //        Amount = string.Format("{0:N}", dt.Rows[0]["Amount"]);
        //        totalAmount = string.Format("{0:N}", dt.Rows[0]["totalAmount"]);
        //    }
        //}
    }
}